package com.gmadmin.service.impl;


import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gmadmin.entity.UnitOrganization;
import com.gmadmin.mapper.UnitOrganizationMapper;
import com.gmadmin.service.UnitOrganizationService;
import com.gmadmin.service.vo.UnitOrganizationVo;
import com.gmadmin.utils.CollectionBeanUtils;
import com.gmadmin.utils.TreeUtil;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Service
public class UnitUnitOrganizationImpl extends ServiceImpl<UnitOrganizationMapper, UnitOrganization> implements UnitOrganizationService {


    private final UnitOrganizationMapper mapper;

    public UnitUnitOrganizationImpl(UnitOrganizationMapper mapper) {
        this.mapper = mapper;
    }

    @Override
    public List<UnitOrganizationVo> findOrganizationTree() {
        List<UnitOrganization> unitOrganizationList = mapper.selectList(null);
        List<UnitOrganizationVo> unitOrganizationVos = CollectionBeanUtils.copyListProperties(unitOrganizationList, UnitOrganizationVo::new);
        List<UnitOrganizationVo> toTree = TreeUtil.listToTree(unitOrganizationVos, UnitOrganizationVo::getId, UnitOrganizationVo::getPid, UnitOrganizationVo::getChildren, UnitOrganizationVo::setChildren,UnitOrganizationVo::getOrganizationSort);

        return toTree;
    }

    @Override
    public List<UnitOrganizationVo> getByUserId(Long userId) {
        List<UnitOrganization> organizations = mapper.selectByUserId(userId);
        List<UnitOrganizationVo> voList = CollectionBeanUtils.copyListProperties(organizations, UnitOrganizationVo::new);
        return voList;
    }

    @Override
    public List<UnitOrganizationVo> getChildNode(Long root, List<UnitOrganizationVo> allList) {

        List<UnitOrganizationVo> child = new ArrayList<>();
        for (UnitOrganizationVo vo : allList) {
            if (root == null || vo.getPid() == root) {
                // 递归查询此节点下的所有子节点
                List<UnitOrganizationVo> childNode = getChildNode(vo.getId(), allList);
                vo.setChildren(childNode);
                child.add(vo);
            }
        }
        // 子节点进行排序
        List<UnitOrganizationVo> childSortVo = Optional.ofNullable(child)
                .map(List::stream)
                .orElseGet(Stream::empty)
                .sorted(Comparator.comparing(UnitOrganizationVo::getOrganizationSort))  // 排序字段
                .collect(Collectors.toList());

        return childSortVo;
    }


}
